package xarticle

import (
	"strings"
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gorm.io/gorm"
)

// 添加文章点赞量
//
//	id	文章ID
//	uid	点赞用户ID
//	typ	点赞类型
//	ip	点赞用户IP地址
func Like(id, uid, typ uint, ip string) error {
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	if ip == "..1" || ip == "127.0.0.1" {
		ip = ""
	}
	article := ArticleLike{
		ArticleId: id,
		UserId:    uid,
		Ip:        ip,
		LikeType:  typ,
		CreatedAt: time.Now().Format(time.DateTime),
	}
	// 插入文章点赞记录
	err := _default.DB.Create(&article).Error
	if err != nil {
		if strings.Index(err.Error(), "Duplicate entry") > 0 {
			return xerror.New("您已经操作过")
		}
		return err
	}
	if typ == LikeArticleLike || typ == LikeArticleCollect {
		// 修改文章点赞/收藏量
		ar, err := Info(id)
		if err != nil {
			return err
		}
		if typ == LikeArticleLike {
			ar.GiveLikeNum++
		} else {
			ar.CollectNum++
		}
		err = _default.DB.Table(_default.ArticleName).Select("give_like_num", "collect_num").Save(ar).Error
		if err != nil {
			return err
		}
		// 修改缓存的浏览量
		xcache.SetStruct(xcache.Key("xarticle.Info", id), ar)
	} else if typ == LikeCommentLike {
		// 评论点赞
		if err := _default.DB.Table(_default.ArticleCommentName).Update("give_like_num", gorm.Expr("give_like_num + ?", 1)).Error; err != nil {
			return err
		}
	}
	return nil
}
